//
//  RadioPlay.m
//  news
//
//  Created by lanou on 15/12/18.
//  Copyright © 2015年 lanou. All rights reserved.
//

#import "RadioPlay.h"
#import "RadioListModel.h"
#import "PlaySingleRadioModel.h"
#import "PlayRadioModel.h"
#import "SingleRadioListModel.h"

@implementation RadioPlay
{
    NSTimer *timer;
    float progress;
}

static RadioPlay *radioPlay;
+ (RadioPlay *)sharedRadioPlay {
    static dispatch_once_t oneToken;
    dispatch_once(&oneToken, ^{
        radioPlay = [[RadioPlay alloc] init];
    });
    return radioPlay;
}

- (instancetype)init {
    self = [super init];
    if (self) {
        // 发送播放结束的通知
        [[NSNotificationCenter defaultCenter] postNotificationName:AVPlayerItemDidPlayToEndTimeNotification object:nil];
    }
    return self;
}

// 开始播放
- (void)startPlaySong {
    if (self.readyToPlay == YES) {
        AVAudioSession *session = [[AVAudioSession alloc] init];
        [session setActive:YES error:nil];
        [session setCategory:AVAudioSessionCategoryPlayback error:nil];
        [self.player play];
        [timer invalidate];// 计时器开始的时候置空
        timer = [NSTimer scheduledTimerWithTimeInterval:0.05 target:self selector:@selector(rotatingAction) userInfo:nil repeats:YES];
    }
}

// 停止播放
- (void)stopPlaySong {
    // 停止
    [self.player pause];
    // 将可播放改为不可播放
    self.readyToPlay = NO;
    // 销毁timer内存
    [timer invalidate];
    // 置空安全释放
    timer = nil;
}

// 下一个
- (void)nextRadio {
    self.item += 1;
    [self loadRadioInfo1];
}

// 上一个
- (void)prevRadio {
    if (self.item == 0) {
        self.item = 0;
    }else {
        self.item -= 1;
        [self loadRadioInfo1];
    }
}

// 图片旋转
- (void)rotatingAction  {
    
//    NSLog(@"转");
    
    progress = self.playerItem.currentTime.value / self.playerItem.currentTime.timescale;

    [self.radioPlayerDelegate audioManagerRadioProgress:progress];

    NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithDictionary:[MPNowPlayingInfoCenter defaultCenter].nowPlayingInfo];
    // 获取当前音乐已经播放的时间
    [dict setValue:[NSNumber numberWithFloat:CMTimeGetSeconds(self.player.currentTime)] forKey:MPNowPlayingInfoPropertyElapsedPlaybackTime];
    // 播放速度
    [dict setValue:[NSNumber numberWithDouble:1.0] forKey:MPNowPlayingInfoPropertyPlaybackRate];
    // 获取我们的总时间
    [dict setValue:[NSNumber numberWithFloat:CMTimeGetSeconds(self.player.currentItem.duration)] forKey:MPMediaItemPropertyPlaybackDuration];
    
    // 将时间加入我们的单例中
    [[MPNowPlayingInfoCenter defaultCenter] setNowPlayingInfo:dict];
    
}

// 指定位置播放
- (void)seekToTime:(CGFloat)time {
    
    // 如果当前歌曲是可播放模式
    if (self.readyToPlay == YES) {
        
        // 拖动时停止播放
        //        [self stopPlaySong];
        
        // 传入两个参数
        // 参数1：我们指定的时间值
        // 参数2：我们的媒体文件的频率
        [self.player seekToTime:CMTimeMakeWithSeconds(time, self.player.currentTime.timescale) completionHandler:^(BOOL finished) {
            
            if (finished == YES) {
                [self startPlaySong];
            }
        }];
        
    }else { // 暂停状态下
        
        [self.player seekToTime:CMTimeMakeWithSeconds(time, self.player.currentTime.timescale) completionHandler:nil];
        
    }
}


- (void)loadRadioInfo1 {
    self.playRadioModel = self.radioListArray[self.item];
    [LORequestManger GET:[NSString stringWithFormat:kPlayRadioUrl,self.playRadioModel.docid] success:^(id response) {
        NSDictionary *rootDic = (NSDictionary *)response;
        NSDictionary *dict = rootDic[self.playRadioModel.docid];
        NSDictionary *dic = dict[@"video"][0];
        PlaySingleRadioModel *playSinle = [[PlaySingleRadioModel alloc] init];
        [playSinle setValuesForKeysWithDictionary:dic];
        
        [self playWithURL:playSinle.url_m3u8];
        
        [[NSNotificationCenter defaultCenter] postNotificationName:@"loadData" object:nil];
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"%@",error);
    }];
}

- (AVPlayer *)player {
    if (!_player) {
        _player = [[AVPlayer alloc] init];
    }
    return _player;
}

- (void)playWithURL:(NSString *)url {
    
    // 如果我们的playerItem是存在的那就移除我们的观察者
    if (self.playerItem) {
        [self.playerItem removeObserver:self forKeyPath:@"status"];
    }
    
    // 将 url 内的媒体资源获取到playerItem当中
    self.playerItem = [[AVPlayerItem alloc] initWithURL:[NSURL URLWithString:url]];
    
    // 添加一个观察者来观察当前的缓冲进度
    [self.playerItem addObserver:self forKeyPath:@"status" options:(NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld) context:nil];
    
    // 替换当前的item
    [self.player replaceCurrentItemWithPlayerItem:self.playerItem];

}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    
    switch ([change[@"new"] integerValue]) {
        case AVPlayerItemStatusFailed:
            NSLog(@"缓冲失败！！！");
            break;
        case AVPlayerItemStatusReadyToPlay:
            self.readyToPlay = YES;
            // 发送一个通知：缓冲成功，可以开始播放
            [[NSNotificationCenter defaultCenter] postNotificationName:@"readyToPlay" object:nil];
            NSLog(@"缓冲成功");
            break;
            
        case AVPlayerItemStatusUnknown:
            NSLog(@"缓冲状态未知");
            break;
            
        default:
            break;
    }
    
}


@end
